<template lang="pug">
  .clearfix
    Modal(
      width="600"
      v-model="isShowPayModal"
      title="申请付款"
    )
      .search-form.mb-10.pl-10.pr-10
        Form.ivu-row.ivu-form-basic(ref="formData" :model="formData" :rules="setRules" :label-width="100")
          FormItem.form-item.ivu-col.pr-20(v-for="(item, index) of setFormItem" :label="item.label" :key="index" :class="item.style" :prop="item.prop")
            template(v-if="item.type === 'select'")
              Select(v-if="item.fn" v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable :disabled="item.isDisabled" @on-change="(event, type) => listenCall(item.fn, item.model, event)")
                Option(v-for="(c_item, c_index) in arrListDown[item.options]" :value="c_item.value" :key="c_index" ) {{ c_item.label }}
              Select(v-else v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable :disabled="item.isDisabled")
                Option(v-for="(c_item, c_index) in arrListDown[item.options]" :value="item.model == 'payType' ? c_item.label : c_item.value" :key="c_index" ) {{ c_item.label }}
            template(v-if="item.type === 'input'")
              Input(v-model="formData[item.model]" :placeholder="item.placeholder" clearable)
            template(v-if="item.type === 'upload'")
              Upload.pull-left.mb-5(
                ref="upload"
                :show-upload-list="false"
                accept=".doc, .docx, .xls, .xlsx, .pptx, .jpg, .jpeg, .png, .rar"
                :action="baseUrl + '/api/FinanceSSPayable/AnnexUpload?categoryName=公积金生成付款单'"
                :on-success="uploadSuccess"
                :headers="headers"
                :max-size="10 * 1024"
                :on-exceeded-size="handleMaxSizeTen"
              )
                Button.download-btn(type="info") 附件上传
              div.pull-left.line-h-32.ml-10(v-if="fileObj && fileObj.Id")
                span.mr-10 {{fileObj.Name}}
                Icon.cursor-pointer.text-error(type="ios-close-circle" @click="removeFile")

      .clearfix(slot="footer")
        Button(type="text" @click="cancel") 关闭
        Button(type="primary" @click="handleSubmit" :loading="!isCanSubmit") 确定
</template>

<script>
import { FinanceTreatmentPayableApi } from '@/api/FinanceTreatmentPayable.api.js'
import Cookies from 'js-cookie'
const colStyle = 'ivu-col-span-24'

export default {
  name: '',

  props: {
  },

  computed: {
    isWorkFlow () {
      const workFlow = (JSON.parse(localStorage.getItem('clientLoginInfo'))).data.workFlow == 'true' ? true : false
      return workFlow
    },

    setRules () {
      if (this.formData.auditType == 1) {
        console.log('垫款金额字段 隐藏')
        this.rules.advanceAmt = []
      } else if (this.formData.auditType == 2) {
        console.log('垫款金额字段 显示')
        this.rules.advanceAmt = [{ required: true, message: '请输入垫款金额', trigger: 'change' }, { validator: this.validateAmt, trigger: 'blur' }]
      }
      return this.rules
    },

    setFormItem () {
      if (this.isWorkFlow) {
        return this.formItem
      } else {
        return [...this.formItem.slice(0, 7)]
      }
    }
  },

  components: {},

  data () {
    const validateAmt = (rule, value, callback) => {
      if (value <= 0) {
        callback(new Error('金额不能为0和负数'))
      } else {
        callback()
      }
    }

    return {
      headers: {
        'Authorization': 'Bearer ' + Cookies.get('clientToken')
      },
      baseUrl: baseUrl,
      isShowPayModal: false,
      isCanSubmit: true,
      record: null,
      WFContent: null,
      formData: {
        // tPBillsID: null,
        accountName: '',
        accountBank: '',
        accountNo: '',
        payType: '',
        applyTotal: '',
        remark: '',
        auditType: null,
        advanceAmt: null,
        explain: null,
        annexId: null
      },
      formItem: [
        { type: 'input', label: '账号名称：', placeholder: '请输入账号名称', prop: 'accountName', model: 'accountName', style: colStyle },
        { type: 'input', label: '开户行：', placeholder: '请输入开户行', prop: 'accountBank', model: 'accountBank', style: colStyle },
        { type: 'input', label: '收款账号：', placeholder: '请输入收款账号', prop: 'accountNo', model: 'accountNo', style: colStyle },
        { type: 'select', label: '付款方式：', placeholder: '请选择付款方式', prop: 'payType', model: 'payType', style: colStyle, options: 'payTypeOps', },
        { type: 'input', label: '请款金额：', placeholder: '请输入请款金额', prop: 'applyTotal', model: 'applyTotal', style: colStyle },
        { type: 'input', label: '付款说明：', placeholder: '请输入付款说明', prop: 'remark', model: 'remark', style: colStyle },
        { type: 'upload', label: '附件上传：', placeholder: '附件上传', prop: 'annexId', model: 'annexId', style: colStyle },
        { type: 'select', label: '审批方式：', placeholder: '请选择审批方式', prop: 'auditType', model: 'auditType', style: 'ivu-col-span-12', options: 'auditTypeOps', fn: 'auditTypeChange' },
        { type: 'input', label: '垫款金额：', placeholder: '请输入垫款金额', prop: 'advanceAmt', model: 'advanceAmt', style: 'ivu-col-span-12' },
        { type: 'input', label: '说明：', placeholder: '请输入说明', prop: 'explain', model: 'explain', style: 'ivu-col-span-12' },
      ],
      rules: {
        accountName: [
          { required: true, message: '请输入账号名称', trigger: 'change' }
        ],
        payType: [
          { required: true, message: '请选择付款方式', trigger: 'change' }
        ],
        applyTotal: [
          { required: true, message: '请输入请款金额', trigger: 'change' },
          { validator: validateAmt, trigger: 'blur' }
        ],
        remark: [
          { required: true, message: '请输入付款说明', trigger: 'change' }
        ],
        auditType: [
          { required: true, message: '请选择审批方式', trigger: 'change' }
        ],
        advanceAmt: [
          { required: true, message: '请输入垫款金额', trigger: 'change' },
          { validator: validateAmt, trigger: 'blur' }
        ],
      },
      arrListDown: {
        payTypeOps: [{label: '转账', value: '转账'}, {label: '现金', value: '现金'}],
        auditTypeOps: [{label: '常规请款审批', value: '1'}, {label: '垫付请款审批', value: '2'}]
      },
      fileObj: null,
    }
  },

  watch: {
  },

  mounted () {
  },

  methods: {
    // 监听所有调用的方法
    listenCall (methodsWords, ...values) {
      this[methodsWords](...values)
    },

    show (row) {
      this.isShowPayModal = true
      this.record = row
      this.fileObj = null
    },

    cancel () {
      this.isShowPayModal = false
      this.$refs.formData.resetFields()
    },

    // 审批方式改变
    auditTypeChange (model, value) {
      console.log('审批方式改变 model: ', model, ', value: ', value)
      if (value == '1') {
        console.log('垫款金额字段 隐藏')
        this.formItem.map(item => {
          if (item.model == 'advanceAmt') {
            item.style = 'ivu-col-span-12 display-none'
          }
        })
      } else if (value == '2') {
        console.log('垫款金额字段 显示')
        this.formItem.map(item => {
          if (item.model == 'advanceAmt') {
            item.style = 'ivu-col-span-12 display-block'
          }
        })
      }
      this.formData.advanceAmt = null
    },

    handleSubmit () {
      this.$refs.formData.validate((valid) => {
        if (valid) {          
          var params = {
            ...this.formData,
            tPBillsID: this.record.id,
            EmployeeName: this.record.employeeName,
            WFContent: {
              AuditType: this.formData.auditType,
              AdvanceAmt: this.formData.advanceAmt,
              Explain: this.formData.explain,
            }
          }
          console.log('提交 params：', params)
          FinanceTreatmentPayableApi.applyPay(params).then(resp => {
            console.log('申请付款resp: ', resp)
            if (resp.status == 200 && resp.data.success) {
              // this.$Message.success(resp.data.message)
              this.$emit('query')
              this.cancel()
              console.log('返回链接: ', resp.data.message)
              window.open(resp.data.message, '_blank')
            } else {
              this.$Message.error(resp.data.message)
            } 
          })
        }
      })
    },

    // 上传前文件
    handleBeforeUpload (file) {
      var str = file.name.substring(file.name.lastIndexOf('.'), file.name.length)
      if (['.xls', '.xlsx'].indexOf(str) == -1) {
        this.$Message.warning('仅支持上传xlsx文件')
        this.file = null
      } else {
        this.file = file
        console.log('file: ', this.file)
      }
      return false
    },

    // 上传成功
    uploadSuccess (res, row) {
      console.log('上传成功res: ', res)
      console.log('上传成功row: ', row)
      if (res.Code === 200 && res.Success) {
        this.fileObj = res.Data
        this.formData.annexId = res.Data.Id
      } else {
        this.$Message.error({
          content: res.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 普通附件下载
    accessoryDownload (url) {
      console.log('下载url: ', url)
      window.open(url, '_blank')
    },

    // 移除附件
    removeFile () {
      this.fileObj = null
      this.formData.annexId = null
    },

    // 超过10M提示
    handleMaxSizeTen () {
      this.$Message.error({
        content: '您上传的文件太大，上传文件大小不能超过10M',
        duration: 10,
        closable: true
      })
    }
  }
}
</script>
